package com.atguigu.gmall.index.config;

import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.index.feign.GmallPmsClient;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import io.jsonwebtoken.lang.Collections;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

@Configuration
public class BloomFilterConfig {
    //项目启动时初始化BloomFilter：并将一级分类的id存入到bf中
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    GmallPmsClient pmsClient;
    @PostConstruct
    public void init(){
        RBloomFilter<Long> bloomFilter = redissonClient.getBloomFilter("cache:cates:bf");
        //初始化bloomFilter
        ResponseVo<List<CategoryEntity>> listResponseVo = pmsClient.queryCategoriesByParentId(0L);
        List<CategoryEntity> categoryEntities = listResponseVo.getData();
        if(!Collections.isEmpty(categoryEntities)){
            bloomFilter.tryInit(categoryEntities.size()+50 , 0.03);
            //将查询到的一级分类的id遍历设置到bf
            categoryEntities.forEach(categoryEntity -> {
                bloomFilter.add(categoryEntity.getId());
            });
        }
    }
}
